package com.example.electricbicycle.controller;

import com.example.electricbicycle.po.Customer;
import com.example.electricbicycle.service.CustomerService;
import com.example.electricbicycle.service.CustomerServiceImpl;
import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.IOException;
import java.util.List;

@WebServlet("/CustomerListServlet")
public class CustomerListServlet extends HttpServlet {
    private final CustomerService customerService = new CustomerServiceImpl();
    private static final int DEFAULT_PAGE_SIZE = 10;

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String pageParam = request.getParameter("page");
        String keyword = request.getParameter("keyword");

        int currentPage = 1;
        if (pageParam != null && !pageParam.isEmpty()) {
            currentPage = Integer.parseInt(pageParam);
        }

        List<Customer> customers;
        int totalCount;

        if (keyword != null && !keyword.isEmpty()) {
            // 搜索时返回所有匹配结果
            customers = customerService.searchCustomers(keyword);
            totalCount = customers.size();
            request.setAttribute("keyword", keyword);
        } else {
            // 非搜索时使用分页
            customers = customerService.getAllCustomers(currentPage, DEFAULT_PAGE_SIZE);
            totalCount = customerService.getTotalCustomerCount();
        }

        int totalPages = (int) Math.ceil((double) totalCount / DEFAULT_PAGE_SIZE);

        // 获取所有客户数据（不分页）
        List<Customer> allCustomers = customerService.getAllCustomers(1, 10000);

        request.setAttribute("customers", customers);
        request.setAttribute("allCustomers", allCustomers); // 添加所有客户数据
        request.setAttribute("currentPage", currentPage);
        request.setAttribute("totalPages", totalPages);
        request.setAttribute("totalCount", totalCount);

        request.getRequestDispatcher("/admin/customerlist.jsp").forward(request, response);
    }
}